package bot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/** Describes an IRC client */
public class Client {
	public static final int CHANNEL_MODE = 324;
	public static final int END_OF_MOTD = 376;
	public static final int NAMES_LIST = 353;
	public static final int NICKNAME_ALREADY_IN_USE = 433;
	
	private String server;
	private int port;

	private Socket socket;
	private BufferedReader input;
	private BufferedWriter output;

	/**
	 * Creates an IRC client
	 * 
	 * @param server
	 *            - Name of the IRC server
	 * @param port
	 *            - The port the server will connect to
	 * @param user
	 *            - The IRC user who will connect to the server
	 */
	public Client(String server, int port) {
		this.server = server;
		this.port = port;
	}

	/** Connects to the server */
	public void connect() {
		try {
			socket = new Socket(server, port);
			socket.setSoTimeout(120000);
			
			InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "UTF8");
			OutputStreamWriter isw = new OutputStreamWriter(socket.getOutputStream(), "UTF8");
			
			input = new BufferedReader(isr);
			output = new BufferedWriter(isw);
			
		} catch (Exception e) {
			try {
				System.out.println("HEJ");
				Thread.sleep(5000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			connect();
		}
	}
	
	public boolean isConnected() {
		return socket.isConnected();
	}

	/** Reads the next incoming line from the IRC server */
	protected String readLine() throws SocketTimeoutException {
		String line = null;
		try {
			line = input.readLine();
		} catch (IOException e) {
			e.printStackTrace();			
		}
		System.out.println(line);
		return line;
	}

	/**
	 * Writes a line to the server
	 * 
	 * @param line
	 *            - The line that the server will receive
	 */
	public void write(String line) {
		try {
			output.write(line + "\n");
			System.out.println(line);
			output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getServer() {
		return server;
	}
}
